package cn.topcodes.tcsf.admin.web.controller.impl;

import cn.topcode.unicorn.utils.ValidationUtil;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.admin.domain.form.BaseSettings;
import cn.topcodes.tcsf.admin.domain.form.EmailConfig;
import cn.topcodes.tcsf.admin.service.EmailService;
import cn.topcodes.tcsf.admin.service.SystemSettingsService;
import cn.topcodes.tcsf.admin.commons.api.security.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

@Controller
@RequestMapping("/admin/sys-settings")
public class SysSettingsController {

	@Autowired
	private SystemSettingsService systemSettingsService;

	@Autowired
	private EmailService emailService;

	/*系统设置页面*/
	@RequestMapping(value="",method=RequestMethod.GET)
	public String index(Model model) {
		BaseSettings baseSettings = this.systemSettingsService.getBaseSettings();
		model.addAttribute("baseSettings",baseSettings);
		EmailConfig emailConfig = this.emailService.getEmailConfig();
		model.addAttribute("emailConfig",emailConfig);
		return "admin/sys-settings";
	}

	@ResponseBody
	@RequestMapping(value = "base-settings",method = RequestMethod.POST)
	public ApiResponseEntity<Void> baseSettings(
			@Valid BaseSettings baseSettings, BindingResult result) {
		ValidationUtil.validate(result);
		systemSettingsService.setBaseSettings(ShiroUtil.getUserId(), baseSettings);
		return ApiResponseEntity.buildOK();
	}

	@ResponseBody
	@RequestMapping(value = "test-email-config",method = RequestMethod.POST)
	public ApiResponseEntity<Void> testEmailConfig(
			@Valid EmailConfig emailConfig, BindingResult result) {
		ValidationUtil.validate(result);
		try {
			emailService.test(emailConfig);
		}catch (Exception e) {
			return ApiResponseEntity.buildFailed(e.getMessage());
		}
		return ApiResponseEntity.buildOK();
	}

	@ResponseBody
	@RequestMapping(value = "email-config",method = RequestMethod.POST)
	public ApiResponseEntity<Void> emailConfig(
			@Valid EmailConfig emailConfig, BindingResult result) {
		ValidationUtil.validate(result);
		emailService.setEmailConfig(emailConfig);
		return ApiResponseEntity.buildOK();
	}
}
